import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import { ModdleElement } from 'bpmn-moddle'
import { getBusinessObject, is } from 'bpmn-js/lib/util/ModelUtil'
import { isAny } from 'bpmn-js/lib/features/modeling/util/ModelingUtil'
import { add as collectionAdd } from 'diagram-js/lib/util/Collections'
import BpmnFactory from 'bpmn-js/lib/features/modeling/BpmnFactory'
import getBpmnIconType from './getIconType'

export function isNameSupported(element) {
  return !isAny(element, ['bpmn:Collaboration', 'bpmn:DataAssociation', 'bpmn:Association'])
}

export function isParticipant(element) {
  return is(element, 'bpmn:Participant')
}

// 根据元素获取 name 属性
export function getNameValue(element): string | undefined {
  if (is(element, 'bpmn:TextAnnotation')) {
    return element.businessObject.text
  } else if (is(element, 'bpmn:Group')) {
    const businessObject: ModdleElement = getBusinessObject(element)
    const categoryValueRef = businessObject?.categoryValueRef
    return categoryValueRef?.value
  } else {
    return element?.businessObject.name
  }
}

// 根据输入内容设置 name 属性
export function setNameValue(element, value: string): void {
  const modeling = useModelerStore().getModeling
  const canvas = useModelerStore().getCanvas
  const bpmnFactory: BpmnFactory | undefined = useModelerStore().getModeler?.get('bpmnFactory')
  if (is(element, 'bpmn:TextAnnotation')) {
    modeling?.updateProperties(element, { text: value })
  } else if (is(element, 'bpmn:Group')) {
    const businessObject = getBusinessObject(element)
    const categoryValueRef = businessObject.categoryValueRef
    if (!categoryValueRef) {
      initializeCategory(businessObject, canvas?.getRootElement(), bpmnFactory)
    }
    modeling?.updateLabel(element, value)
  } else {
    modeling?.updateProperties(element, { name: value })
  }
}

// 初始化节点name值
export function initNameValue(element) {
  const elementId = element.businessObject.id
  console.log(elementId, '当前节点id')
  console.log(useModelerStore().getActiveId, '当前选中节点id')
  if (element.type !== 'label' && elementId !== useModelerStore().getActiveId) {
    let activatedElement = element
    let activatedElementTypeName = ''
    let name = ''
    const modeler = useModelerStore().getModeler
    if (!activatedElement) {
      activatedElement = modeler.get('elementRegistry').find((el) => el.type === 'bpmn:Process') || modeler.get('elementRegistry').find((el) => el.type === 'bpmn:Collaboration')
      if (!activatedElement) {
        name = ''
      }
    }
    activatedElementTypeName = getBpmnIconType(activatedElement)
    name = getDefaultName()[activatedElementTypeName] ? getDefaultName()[activatedElementTypeName] : ''
    if (is(element, 'bpmn:TextAnnotation')) {
      element.businessObject.text = ''
    } else if (is(element, 'bpmn:Group')) {
      const canvas = useModelerStore().getCanvas
      const bpmnFactory: BpmnFactory | undefined = useModelerStore().getModeler?.get('bpmnFactory')
      const businessObject = getBusinessObject(element)
      const categoryValueRef = businessObject.categoryValueRef
      if (!categoryValueRef) {
        initializeCategory(businessObject, canvas?.getRootElement(), bpmnFactory)
      }
      element.businessObject.categoryValueRef.value = name
    } else {
      element.businessObject.name = name
    }
  }
}

// //////////////  helpers

function createCategoryValue(definitions, bpmnFactory): ModdleElement {
  const categoryValue = bpmnFactory.create('bpmn:CategoryValue')
  const category = bpmnFactory.create('bpmn:Category', {
    categoryValue: [categoryValue]
  })
  collectionAdd(definitions.get('rootElements'), category)
  getBusinessObject(category).$parent = definitions
  getBusinessObject(categoryValue).$parent = category

  return categoryValue
}

function initializeCategory(businessObject, rootElement, bpmnFactory) {
  const definitions = getBusinessObject(rootElement).$parent

  businessObject.categoryValueRef = createCategoryValue(definitions, bpmnFactory)
}

function getDefaultName() {
  return {
    StartEvent: '开始事件',
    EndEvent: '结束事件',
    Task: '任务',
    Association: '关联',
    BusinessRuleTask: '业务规则任务',
    CallActivity: '调用活动',
    Collaboration: '协同',
    ConditionalFlow: '条件流转路径',
    SequenceFlow: '普通流转路径',
    DataInput: '数据输入',
    DataInputAssociation: '数据输入关联',
    DataOutput: '数据输出',
    DataOutputAssociation: '数据输出关联',
    DefaultFlow: '默认流转路径',
    CancelEndEvent: '取消结束事件',
    CompensateEndEvent: '补偿结束事件',
    ErrorEndEvent: '错误结束事件',
    EscalationEndEvent: '上报结束事件',
    LinkEndEvent: '链接结束事件',
    MessageEndEvent: '消息结束事件',
    MultipleEndEvent: '多端事件',
    SignalEndEvent: '信号结束事件',
    TerminateEndEvent: '终止结束事件',
    EventSubProcess: '事件子流程',
    ComplexGateway: '复杂网关',
    EventBasedGateway: '事件网关',
    ExclusiveGateway: '专属网关',
    Gateway: '网关',
    InclusiveGateway: '包容性网关',
    ParallelGateway: '并行网关',
    Group: '组',
    CancelIntermediateCatchEvent: '取消中间捕获事件',
    CompensateIntermediateCatchEvent: '补偿中间捕获事件',
    ConditionalIntermediateCatchEvent: '条件中间捕获事件',
    ErrorIntermediateCatchEvent: '错误中间捕获事件',
    EscalationIntermediateCatchEvent: '上报中间捕获事件',
    LinkIntermediateCatchEvent: '链接中间捕获事件',
    MessageIntermediateCatchEvent: '消息中间捕获事件',
    MultipleIntermediateCatchEvent: '多个中间捕获事件',
    ConditionalIntermediateCatchEventNonInterrupting: '条件中间捕获事件（非中断）',
    EscalationIntermediateCatchEventNonInterrupting: '上报中间捕获事件（非中断）',
    MessageIntermediateCatchEventNonInterrupting: '消息中间捕获事件（非中断）',
    MultipleIntermediateCatchEventNonInterrupting: '多个中间捕获事件（非中断）',
    ParallelIntermediateCatchEventNonInterrupting: '并行中间捕获事件（非中断）',
    SignalIntermediateCatchEventNonInterrupting: '信号中间捕获事件（非中断）',
    TimerIntermediateCatchEventNonInterrupting: '定时中间捕获事件（非中断）',
    ParallelMultipleIntermediateCatchEvent: '并行多个中间捕获事件',
    SignalIntermediateCatchEvent: '信号中间捕获事件',
    TimerIntermediateCatchEvent: '定时中间捕获事件',
    IntermediateCatchEvent: '中间捕获事件',
    IntermediateThrowEvent: '中间抛出事件',
    CompensateIntermediateThrowEvent: '补偿中间抛出事件',
    EscalationIntermediateThrowEvent: '上报中间抛出事件',
    LinkIntermediateThrowEvent: '链接中间抛出事件',
    MessageIntermediateThrowEvent: '消息中间抛出事件',
    MultipleIntermediateThrowEvent: '多个中间抛出事件',
    SignalIntermediateThrowEvent: '信号中间抛出事件',
    Lane: '道',
    ManualTask: '手动任务',
    MessageFlow: '消息流',
    Participant: '参与者',
    ReceiveTask: '接收任务',
    ScriptTask: '脚本任务',
    SendTask: '发送任务',
    ServiceTask: '服务任务',
    CompensateStartEvent: '补偿开始事件',
    ConditionalStartEvent: '条件开始事件',
    ErrorStartEvent: '错误开始事件',
    EscalationStartEvent: '上报开始事件',
    MessageStartEvent: '消息开始事件',
    MultipleStartEvent: '多个开始事件',
    ConditionalStartEventNonInterrupting: '条件开始事件（非中断）',
    EscalationStartEventNonInterrupting: '上报开始事件（非中断）',
    MessageStartEventNonInterrupting: '消息开始事件（非中断）',
    MultipleStartEventNonInterrupting: '多个开始事件（非中断）',
    ParallelMultipleStartEventNonInterrupting: '并行多个开始事件（非中断）',
    SignalStartEventNonInterrupting: '信号开始事件（非中断）',
    TimerStartEventNonInterrupting: '定时开始事件（非中断）',
    CancelBoundaryEvent: '取消边界事件',
    CompensateBoundaryEvent: '补偿边界事件',
    ConditionalBoundaryEvent: '条件边界事件',
    ErrorBoundaryEvent: '错误边界事件',
    EscalationBoundaryEvent: '上报边界事件',
    LinkBoundaryEvent: '链接边界事件',
    MessageBoundaryEvent: '消息边界事件',
    MultipleBoundaryEvent: '多个边界事件',
    BoundaryEvent: '边界事件',
    ConditionalBoundaryEventNonInterrupting: '条件边界事件（非中断）',
    EscalationBoundaryEventNonInterrupting: '上报边界事件（非中断）',
    MessageBoundaryEventNonInterrupting: '消息边界事件（非中断）',
    MultipleBoundaryEventNonInterrupting: '多个边界事件（非中断）',
    ParallelBoundaryEventNonInterrupting: '并行边界事件（非中断）',
    SignalBoundaryEventNonInterrupting: '信号边界事件（非中断）',
    TimerBoundaryEventNonInterrupting: '定时边界事件（非中断）',
    ParallelMultipleBoundaryEvent: '并行多个边界事件',
    SignalBoundaryEvent: '信号边界事件',
    TimerBoundaryEvent: '定时边界事件',
    ParallelMultipleStartEvent: '并行多个开始事件',
    SignalStartEvent: '信号开始事件',
    TimerStartEvent: '定时开始事件',
    CollapsedSubProcess: '子流程（折叠的）',
    CollapsedAdHocSubProcess: '即席子流程（折叠的）',
    ExpandedSubProcess: '子流程（展开的）',
    ExpandedAdHocSubProcess: '即席子流程（展开的）',
    AdHocSubProcess: '即席子流程',
    UserTask: '用户任务',
    DataObjectReference: '数据对象参考',
    DataStoreReference: '数据存储参考'
  }
}
